package meituan;

import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 54. 螺旋矩阵:https://leetcode-cn.com/problems/spiral-matrix/
 * @Author luozhenting
 * @Date 2021/10/15
 **/
public class SpiralOrder {
    // 右-》下-》左-》上
    int x = 0;
    int y = 0;
    int direction = 0;
    boolean[][] status;

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        int m = matrix.length;
        if (m == 0) {
            return list;
        }
        int n = matrix[0].length;
        int size = m * n;
        status =  new boolean[m][n];

        list.add(matrix[x][y]);
        status[x][y] = true;
        while (list.size() < size) {
            this.move(m, n);
            list.add(matrix[x][y]);
            status[x][y] = true;
        }

        return list;
    }

    private void move(int m, int n) {

        if (direction == 0 && y < n - 1 && !status[x][y + 1]) { //向右
            y = y + 1;
        } else if (direction == 1 && x < m - 1 && !status[x + 1][y]) {//向下
            x = x + 1;
        } else if (direction == 2 && y > 0 && !status[x][y - 1]) {//向左
            y = y - 1;
        } else if (direction == 3 && x > 0 && !status[x - 1][y]) {//向上
            x = x - 1;
        } else {
            refreshDirection();
            this.move(m, n);
        }
    }

    private void refreshDirection() {
        ++direction;
        if (direction == 4) {
            direction = 0;
        }

    }

    @Test
    public void myTest() {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        System.out.println(this.spiralOrder(matrix));
    }
}
